#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#define MYPORT 8888 //listening port
#define BACKLOG 10 //max connect requests
#define MAXDATASIZE 1024 //max data buff

/** Autuor : zhaoshun
  * Time   : 2017/12/20 17:56
  * Email  : tmby1314@163.com
  **/
int main_socket_server(int argc, char ** argv) {
//int main_socket_server(int argc, char ** argv) {
    int sock_fd,new_fd,fd,numbytes;
    struct sockaddr_in my_addr;
    struct sockaddr_in their_addr;
    int sin_size;
    char buf[MAXDATASIZE];  /*socket()*/
    if((sock_fd=socket(AF_INET,SOCK_STREAM,0))==-1)  {
        perror("socket create error");   exit(1);
    }
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(MYPORT);
    my_addr.sin_addr.s_addr = INADDR_ANY;
    bzero(&(my_addr.sin_zero),8);   /*bind()*/
    if(bind(sock_fd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)  {
        perror("bind error");   exit(1);
    }
    /*listen()*/
    if(listen(sock_fd,BACKLOG)==-1)  {
        perror("listen error");
        exit(1);
    }

    while(1)  {
        sin_size=sizeof(struct sockaddr_in);
        if((new_fd=accept(sock_fd,(struct sockaddr *)&their_addr,&sin_size))==-1)   {
            perror("accept error");
            continue;

        }     printf("received a connect from:%s\n",inet_ntoa(their_addr.sin_addr));   /*recv()*/
        fd=open("/home/neo/CLionProjects/CDataStruct/shanghaiJD/forthJob/a.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);
        while (( numbytes = recv(new_fd, buf, MAXDATASIZE, 0)) > 0)   {
            write(fd,buf,numbytes);
        }
        close(new_fd);
        close(fd);
        printf("File successfully received.\n");      /* clean up child processes */
        while(waitpid(-1,NULL,WNOHANG) > 0);
    }
}